package com.pm.project.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.pm.common.OAService;
import com.pm.common.annotation.DataSource;
import com.pm.common.config.PMConfig;
import com.pm.common.config.ParamConfig;
import com.pm.common.constant.ProjectConstants;
import com.pm.common.core.domain.AjaxResult;
import com.pm.common.core.domain.TreeSelect;
import com.pm.common.core.domain.entity.*;
import com.pm.common.core.domain.model.LoginUser;
import com.pm.common.enums.DataSourceType;
import com.pm.common.enums.DelFlagEnum;
import com.pm.common.enums.ProjectListStatusEnum;
import com.pm.common.mapper.OaMapper;
import com.pm.common.utils.*;
import com.pm.common.utils.email.EmailUtils;
import com.pm.common.utils.email.MailRequest;
import com.pm.common.utils.poi.ExcelUtil;
import com.pm.project.domain.*;
import com.pm.project.domain.vo.OverdueTaskListVO;
import com.pm.project.domain.vo.ProjectListMemberVO;
import com.pm.project.domain.vo.ProjectListVO;
import com.pm.project.mapper.*;
import com.pm.project.service.ProjectListService;
import com.pm.system.domain.SysConfig;
import com.pm.system.mapper.SysConfigMapper;
import com.pm.system.mapper.SysUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ProjectListServiceImpl implements ProjectListService {

    Logger logger = LoggerFactory.getLogger(ProjectListServiceImpl.class);


    @Resource
    ProjectListMapper projectListMapper;

    @Resource
    ProjectListMemberMapper projectListMemberMapper;
    @Resource
    ProjectListNodeMemberMapper projectListNodeMemberMapper;


    @Resource
    ProjectListNodeMapper projectListNodeMapper;

    @Resource
    OAService oaService;

    @Resource
    ParamConfig paramConfig;

    @Resource
    SysUserMapper sysUserMapper;

    @Resource
    ProjectModifyRecordMapper projectModifyRecordMapper;

    @Resource
    ProjectModifyRecordDetailMapper projectModifyRecordDetailMapper;

    @Resource
    SysConfigMapper sysConfigMapper;

    @Resource
    OaUtils oaUtils;

    @Resource
    OaMapper oaMapper;

    @Resource
    EmailUtils emailUtils;

    @Resource
    WeChatUtils weChatUtils;

    @Resource
    ProjectListStopMapper projectListStopMapper;




    /**
     * 查询项目列表
     * @param projectList
     * @return
     */
    @Override
    public List<ProjectListVO> list(ProjectList projectList) {

        MPJLambdaWrapper<ProjectList> query = JoinWrappers.lambda(ProjectList.class);
        query.innerJoin(SysUser.class,"s",SysUser::getUserId,ProjectList::getCreateBy)
                .innerJoin(SysUser.class,"m",SysUser::getUserId,ProjectList::getProjectManager)
                .eq(ProjectTempleteVersion::getDelFlag,0)//未删除的数据
                .selectAs("s",SysUser::getNickName, ProjectListVO::getNickName)
                .selectAs("m",SysUser::getNickName, ProjectListVO::getProjectManagerName)
                .selectAll(ProjectList.class);

        if(StringUtils.isNotBlank(projectList.getProjectNo())){
            query.eq(ProjectList::getProjectNo,projectList.getProjectNo());
        }


        if(StringUtils.isNotBlank(projectList.getProductName())){
            query.like(ProjectList::getProductName,projectList.getProductName());
        }

        if(projectList.getProjectManager() != null){
            query.eq(ProjectList::getProjectManager,projectList.getProjectManager());
        }

        //只查询自己的项目
        if("1".equals(projectList.getMyProjectFlag())){
            query.eq(ProjectList::getProjectManager,SecurityUtils.getUserId());
        }

        if(StringUtils.isNotBlank(projectList.getPrdOaNo())){
            query.eq(ProjectList::getPrdOaNo,projectList.getPrdOaNo());
        }

        if(StringUtils.isNotBlank(projectList.getMrdOaNo())){
            query.eq(ProjectList::getMrdOaNo,projectList.getMrdOaNo());
        }

        if(StringUtils.isNotBlank(projectList.getProductType())){
            query.eq(ProjectList::getProductType,projectList.getProductType());
        }


        if(StringUtils.isNotBlank(projectList.getProductLine())){
            query.eq(ProjectList::getProductLine,projectList.getProductLine());
        }


        if(projectList.getOverdue() != null){
            if(projectList.getOverdue() == 1){
                query.gt(ProjectList::getOverdue,0);
            }else{
                query.eq(ProjectList::getOverdue,projectList.getOverdue());
            }

        }

        return projectListMapper.selectJoinList(ProjectListVO.class,query);

    }

    /**
     * 添加项目
     * @param projectList
     * @return
     */
    @Override
    @Transactional
    public AjaxResult add(ProjectList projectList) {

        //先判断项目编号是否存在
        QueryWrapper<ProjectList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_no",projectList.getProjectNo()).le("status",10000);
        List<ProjectList> projects = projectListMapper.selectList(queryWrapper);
        if(!CollectionUtils.isEmpty(projects)){
            return AjaxResult.error("项目编号已经存在!");
        }

        //添加项目
        LoginUser loginUser = SecurityUtils.getLoginUser();
        projectList.setCreateBy(loginUser.getUserId());
        projectList.setCreateTime(new Date());
        projectListMapper.insert(projectList);

        //项目经理
        ProjectListMemberVO projectListMemberVO = new ProjectListMemberVO();
        projectListMemberVO.setType(ProjectConstants.PJMPOSTCODE);
        projectListMemberVO.setUserId(projectList.getProjectManager());

        //添加项目成员·
        if(!CollectionUtils.isEmpty(projectList.getProjectListMemberList())){
            //默认添加项目经理
            projectList.getProjectListMemberList().add(projectListMemberVO);
        }else{
            List<ProjectListMemberVO> list = new ArrayList<>();
            list.add(projectListMemberVO);
            projectList.setProjectListMemberList(list);
        }

        List<String> keys = new ArrayList<>();


        projectList.getProjectListMemberList().forEach(item->{

            String key = item.getType()+"_"+item.getUserId();
            if(!keys.contains(key)){
                item.setProjectListId(projectList.getId());
                projectListMemberMapper.insert(item);
                keys.add(key);
            }

        });

        addProjectOperLog(projectList.getId(),ProjectListStatusEnum.DRAFT.getStatus(),"创建项目");

        //生成代办消息提醒DQA
        noticeOAToDQA(projectList);

        return AjaxResult.success("操作成功!");
    }

    private void addProjectOperLog(Long projectListId, Integer status, String remark) {
         LoginUser loginUser = SecurityUtils.getLoginUser();
         JSONObject param = new JSONObject();
         param.put("projectListId",projectListId);
         param.put("status",status);
         param.put("remark",remark);
         param.put("userId",loginUser.getUserId());
         projectListMapper.addLog(param);
    }

    /**
     * 代办消息推送DQA
     * @param
     */
    private void noticeOAToDQA(ProjectList projectList) {
        try{
            SysConfig sysConfig = new SysConfig();
            sysConfig.setConfigKey(ProjectConstants.PROJECT_LIST_SET_NOTICE);
            SysConfig jobNumbers = sysConfigMapper.selectConfig(sysConfig);
            if(jobNumbers == null){
                return;
            }
            if(StringUtils.isBlank(jobNumbers.getConfigValue())){
                return;
            }
            String[] jobs = jobNumbers.getConfigValue().split(";");
            List<String> noticUsers = Arrays.stream(jobs).collect(Collectors.toList());

            String token = weChatUtils.getAccessToken();
            String subject = ProjectConstants.OA_TODO_SUBJECT+": "+projectList.getProductName()+" 待设置节点!";
            AjaxResult res = weChatUtils.sendTextMessage(token,subject,noticUsers);
            if(res.isError()){
                logger.error("创建项目发送代办消息错误:"+res.get(AjaxResult.MSG_TAG));
            }

        }catch (Exception e){
            logger.error("发送代办消息错误:"+JSONObject.toJSONString(projectList));
        }

    }


    @Override
    @Transactional
    public AjaxResult modify(ProjectList projectList) {

        String remark = "修改项目";
        LoginUser loginUser = SecurityUtils.getLoginUser();
        projectList.setUpdateTime(new Date());
        projectList.setUpdateBy(loginUser.getUserId());
        //如果是提交则修改状态 如果是修改则不改状态
        if(!projectList.getModifyFlag()){
            projectList.setStatus(ProjectListStatusEnum.CREATE.getStatus());
            remark = "重新提交项目";
        }

        projectListMapper.updateById(projectList);

        //修改成员表  先清理 在添加
        QueryWrapper<ProjectListMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_list_id",projectList.getId());
        projectListMemberMapper.delete(queryWrapper);

        //添加项目成员
        if(!CollectionUtils.isEmpty(projectList.getProjectListMemberList())){
            projectList.getProjectListMemberList().forEach(item->{
                item.setProjectListId(projectList.getId());
                projectListMemberMapper.insert(item);
            });
        }


        addProjectOperLog(projectList.getId(),ProjectListStatusEnum.DRAFT.getStatus(),remark);

        if(!projectList.getModifyFlag()){
            noticeOAToDQA(projectList);
        }

        return AjaxResult.success("操作成功!");
    }

    @Override
    public AjaxResult detail(String projectListId) {

        MPJLambdaWrapper<ProjectList> query = JoinWrappers.lambda(ProjectList.class);
        query.innerJoin(SysUser.class,"s",SysUser::getUserId,ProjectList::getCreateBy)
                .innerJoin(SysUser.class,"m",SysUser::getUserId,ProjectList::getProjectManager)
                .selectAs("s",SysUser::getNickName, ProjectListVO::getNickName)
                .selectAs("m",SysUser::getNickName, ProjectListVO::getProjectManagerName)
                .eq(ProjectList::getId,projectListId)
                .selectAll(ProjectList.class);

        List<ProjectListVO> projectLists = projectListMapper.selectJoinList(ProjectListVO.class,query);
        ProjectListVO projectList = projectLists.get(0);

        //判断当期用户是否为项目经理
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(projectList.getProjectManager().equals(loginUser.getUserId())){
            projectList.setProjectManagerFlag("Y");
        }else{
            projectList.setProjectManagerFlag("N");
        }



        MPJLambdaWrapper<ProjectListMember> queryMember = JoinWrappers.lambda(ProjectListMember.class);
        queryMember.innerJoin(SysUser.class,"s",SysUser::getUserId,ProjectListMember::getUserId)
                .innerJoin(SysDictData.class,"m",SysDictData::getDictValue,ProjectListMember::getType)
                .selectAs("m",SysDictData::getDictLabel, ProjectListMemberVO::getTypeName)
                .selectAs("s",SysUser::getNickName, ProjectListMemberVO::getProjectManagerName)
                .eq(ProjectListMember::getProjectListId,projectListId)
                .eq(SysDictData::getDictType,"owner_position")
                .selectAll(ProjectListMemberVO.class);

        projectList.setProjectListMemberList(projectListMemberMapper.selectJoinList(ProjectListMemberVO.class,queryMember));
        return AjaxResult.success(projectList);
    }


    /**
     * 删除项目
     * @param projectList
     * @return
     */
    @Override
    public AjaxResult delete(ProjectList projectList) {

        //校验项目状态 草稿状态才能删除
        ProjectList detail = projectListMapper.selectById(projectList);
        if(detail.getStatus().intValue() != ProjectListStatusEnum.DRAFT.getStatus().intValue()){
               return  AjaxResult.error("草稿状态的项目才能删除!");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        ProjectList update = new ProjectList();
        update.setId(projectList.getId());
        update.setDelFlag(DelFlagEnum.CANCEL.getStatus().toString());
        update.setUpdateTime(new Date());
        update.setUpdateBy(loginUser.getUserId());
        projectListMapper.deleteById(update);
        return AjaxResult.success("操作成功!");
    }

    /**
     * 项目中止
     * @param projectList
     * @return
     */
    @Override
    public AjaxResult stop(ProjectList projectList) {

        ProjectList obj =  projectListMapper.selectById(projectList.getId());

        //添加中止记录表
        LoginUser loginUser = SecurityUtils.getLoginUser();
        ProjectListStop projectListStop = new ProjectListStop();
        projectListStop.setProjectListStatus(obj.getStatus());
        projectListStop.setProjectListId(projectList.getId());
        projectListStop.setCreateBy(loginUser.getUserId());
        projectListStop.setCreateTime(new Date());
        projectListStop.setStatus(1);
        projectListStopMapper.insert(projectListStop);

        //修改项目状态
        ProjectList update = new ProjectList();
        update.setId(projectList.getId());
        update.setStatus(ProjectListStatusEnum.STOP.getStatus());
        update.setUpdateTime(new Date());
        update.setUpdateBy(loginUser.getUserId());
        projectListMapper.updateById(update);

        addProjectOperLog(projectList.getId(),ProjectListStatusEnum.STOP.getStatus(),"中止项目");
        return AjaxResult.success("操作成功!");
    }

    @Override
    public AjaxResult draft(ProjectList projectList) {

        if(projectList.getId() != null){
            return  modify(projectList);
        }else{
            projectList.setStatus(ProjectListStatusEnum.DRAFT.getStatus());
            return  add(projectList);
        }
    }

    @Override
    public AjaxResult getSetupDetail(Long projectListId) {
        JSONObject res = new JSONObject();
        //查询节点信息
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();


        List<ProjectTempleteDefine> nodes = projectListNodeMapper.getProjectNodes(projectListId,sysUser.getUserId());
        if(!CollectionUtils.isEmpty(nodes)){

            List<ProjectTempleteDefine>  treeList = ProjectUtils.buildProjectTempleteDefineTree(nodes);
            List<TreeSelect> ts = treeList.stream().map(TreeSelect::new).collect(Collectors.toList());
            //版本号
            res.put("versionNo",nodes.get(0).getVersionNo());
            //树状接口任务列表
            res.put("trees",ts);

            res.put("treeList",treeList);

            //计算里程碑完成率
            if(!CollectionUtils.isEmpty(treeList)){
                for (ProjectTempleteDefine projectTempleteDefine : treeList) {
                    JSONObject param = new JSONObject();
                    param.put("total",0);
                    param.put("doneNum",0);
                    calculateDoneRate(projectTempleteDefine,param);
                    BigDecimal rate = BigDecimal.ZERO;
                    if(param.getBigDecimal("total") != BigDecimal.ZERO){
                        rate = param.getBigDecimal("doneNum").divide(param.getBigDecimal("total"),2,RoundingMode.HALF_DOWN);
                    }
                    projectTempleteDefine.setDoneRate(rate.multiply(BigDecimal.valueOf(100)));
                }
            }



        }
        return AjaxResult.success(res);
    }

    private void calculateDoneRate(ProjectTempleteDefine projectTempleteDefine,JSONObject param) {

        if(projectTempleteDefine.getChildren()!= null && projectTempleteDefine.getChildren().size() > 0){


            for (ProjectTempleteDefine child : projectTempleteDefine.getChildren()) {
                calculateDoneRate(child,param);
            }

        }else{
            if(!CollectionUtils.isEmpty(projectTempleteDefine.getProjectListNodeMemberList())){
                for (ProjectListNodeMember projectListNodeMember : projectTempleteDefine.getProjectListNodeMemberList()) {
                    int total = param.getIntValue("total");
                    int doneNum = param.getIntValue("doneNum");
                    total++;
                    if(projectListNodeMember.getStatus() !=  null && projectListNodeMember.getStatus() == 10){
                        doneNum++;
                        param.put("doneNum",doneNum);
                    }
                    param.put("total",total);
                }
            }
        }
    }




    /**
     * 设置项目
     * @param param
     * @return
     */
    @Override
    @Transactional
    public AjaxResult saveSetUp(JSONObject param) {
        Set<String> nodeIds = new HashSet<>();

        //先删除数据
        QueryWrapper<ProjectListNode> del = new QueryWrapper<>();
        del.eq("project_list_id",param.getLong("projectId"));
        projectListNodeMapper.delete(del);

        //获取任务节点
        JSONArray array = param.getJSONArray("checkedNodeList");
        if(!CollectionUtils.isEmpty(array)){
            for(int i=0;i< array.size();i++){
                JSONObject item = array.getJSONObject(i);
                nodeIds.add(item.getString("id"));
            }
            param.put("nodeIds",nodeIds);
            projectListNodeMapper.addProjectNodes(param);

            LoginUser sysUser = SecurityUtils.getLoginUser();
            ProjectList projectList = new ProjectList();
            projectList.setId(param.getLong("projectId"));
            projectList.setStatus(ProjectListStatusEnum.DEFINE.getStatus());
            projectList.setUpdateTime(new Date());
            projectList.setUpdateBy(sysUser.getUserId());
            projectListMapper.updateById(projectList);
        }

        addProjectOperLog(param.getLong("projectId"),ProjectListStatusEnum.CREATE.getStatus(),"设置项目节点");

        ProjectList projectList = projectListMapper.selectById(param.getLong("projectId"));
        SysUser  projectManager  = sysUserMapper.selectUserById(projectList.getProjectManager());
        String subject =ProjectConstants.OA_TODO_SUBJECT+ projectList.getProjectNo()+"项目,机型:"+projectList.getProductName()+"待设置人员和时间,请及时登陆PM系统处理!";
        String token = weChatUtils.getAccessToken();
        List<String> noticUsers = new ArrayList<>();
        noticUsers.add(projectManager.getCompanyWechatId());
        AjaxResult res = weChatUtils.sendTextMessage(token,subject,noticUsers);
        if(res.isError()){
            logger.error("保存节点设置 发送企业微信消息给项目经理错误:"+res.get(AjaxResult.MSG_TAG));
        }
        return AjaxResult.success("操作成功!");
    }

    @Override
    public List<ProjectListVO> setupList(ProjectList projectList) {
        return  projectListMapper.setupList(projectList);

    }

    /**
     * 设置项目时间和责任人
     * @param param
     * @return
     */
    @Override
    @Transactional
    public AjaxResult saveSettimeMember(JSONObject param) {

        //更新项目状态
        LoginUser loginUser = SecurityUtils.getLoginUser();
        ProjectList projectList = new ProjectList();
        projectList.setId(param.getLong("id"));
        projectList.setStatus(ProjectListStatusEnum.WAY.getStatus());
        projectList.setUpdateBy(loginUser.getUserId());
        projectList.setUpdateTime(new Date());
        projectListMapper.updateById(projectList);

        Map<String,JSONObject> map = new HashMap<>();

        //递归更新节点信息
        JSONArray nodes = param.getJSONArray("nodes");
        if(!CollectionUtils.isEmpty(nodes)){


            ProjectList project = projectListMapper.selectById(param.getLong("id"));

            //跟节点时间更新
            rootNodesTimes(nodes,project.getProjectNo());

            //添加节点任务成员信息
            addNodeMembers(nodes,map);

            //先清空项目成员表
            QueryWrapper<ProjectListMember> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("project_list_id",param.getLong("id"));
            projectListMemberMapper.delete(queryWrapper);

            //添加项目成员
            projectListMemberMapper.addList(map,param.getLong("id"),loginUser.getUserId());

            //生成代办信息
            List<String> noticUsers = sysUserMapper.queryJobNoByMap(map);
            String subject = ProjectConstants.OA_TODO_SUBJECT+":项目"+project.getProductName()+" 你有新的待办任务!";
            String token = weChatUtils.getAccessToken();
            AjaxResult res = weChatUtils.sendTextMessage(token,subject,noticUsers);
            if(res.isError()){
                logger.error("生成PM任务代办信息错误:"+res.get(AjaxResult.MSG_TAG));
            }
//            oaService.createWaitTaskNotice("/project/TaskList&projectNo="+project.getProjectNo(),toUsers,ProjectConstants.OA_TODO_SUBJECT+": 你有新的待完成任务!");

        }

        addProjectOperLog(param.getLong("id"),ProjectListStatusEnum.DEFINE.getStatus(),"设置项目时间和责任人");
        return AjaxResult.success("操作成功!");
    }

//    private void createWaitTaskNotice(String redirect,List<JSONObject> toUsers,String subject) {
//
//        JSONObject param = new JSONObject();
//        param.put("appName",ProjectConstants.PM);
//        param.put("modelName",ProjectConstants.OA_TODO_MODEL_NAME);
//        param.put("modelId",ProjectConstants.OA_TODO_MODEL_ID);
//        param.put("subject",subject);
//        String url = paramConfig.getOaAddr()+"/pro/sso/proSsoRequest.do?method=login&service="+URLEncoder.encode(paramConfig.getPmAddr() +"/login?redirect="+redirect) ;
//        param.put("link", url);
//        param.put("mobileLink",url);
//        param.put("padLink",url);
//        param.put("type","1");
//
//        param.put("targets",JSONObject.toJSONString(toUsers));
//        param.put("createTime",DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD_HH_MM_SS));
//
//        AjaxResult res = oaService.sendTodo(param);
//
//    }

    /**
     * 添加责任人和时间
     * @param nodes
     */
    private void addNodeMembers(JSONArray nodes,Map<String,JSONObject> map) {
        for(int i=0;i<nodes.size();i++){
            JSONObject node = nodes.getJSONObject(i);
            if(!CollectionUtils.isEmpty(node.getJSONArray("children"))){
                addNodeMembers(node.getJSONArray("children"),map);
            }else{
                List<ProjectListNodeMember> list = new ArrayList<>();
                ProjectListNodeMember item = new ProjectListNodeMember();
                item.setProjectListNodeId(node.getLong("pnId"));
                list.add(item);
                JSONArray array = node.getJSONArray("projectListNodeMemberList");
                if(!CollectionUtils.isEmpty(array)){
                   for(int j=0;j<array.size();j++){
                       JSONObject temp = array.getJSONObject(j);
                       ProjectListNodeMember obj = new ProjectListNodeMember();
                       obj.setProjectListNodeId(node.getLong("pnId"));
                       list.add(obj);
                       //添加到成员表
                       String key =  temp.getString("postCode")+temp.getLong("userId");
                       if(!map.containsKey(key)){
                           JSONObject mValue = new JSONObject();
                           mValue.put("ownerPosition",temp.getString("postCode"));
                           mValue.put("ownerUserId",temp.getLong("userId"));
                           map.put(key,mValue);
                       }
                   }
                }
            }

        }

    }

    /**
     * 查询里程碑
     * @param projectList
     * @return
     */
    @Override
    public JSONObject queryMilestone(ProjectList projectList) {
        JSONObject res= new JSONObject();
        List<JSONObject> list = projectListMapper.queryMilestone(projectList);
        int i = 0;
        if(!CollectionUtils.isEmpty(list)){
            for (JSONObject jsonObject : list) {
                if(jsonObject.getIntValue("status") == 10){
                    i++;
                }
            }
        }

        res.put("milestones",list);
        res.put("active",i);
        return res;

    }

    @Override
    public JSONObject queryProgress(ProjectList projectList) {
        List<JSONObject> list =  projectListMapper.queryProgress(projectList);
        BigDecimal progress = BigDecimal.ZERO;
        if(!CollectionUtils.isEmpty(list)){
            int i=0;
            for (JSONObject jsonObject : list) {
                if(jsonObject.getIntValue("status") == 10){
                    i++;
                }
            }
            if(i>0){
                BigDecimal doneNum = BigDecimal.valueOf(i);
                progress = doneNum.divide(BigDecimal.valueOf(list.size()),2, RoundingMode.HALF_UP);
            }

        }

        JSONObject res = new JSONObject();
        res.put("progress",progress.multiply(BigDecimal.valueOf(100)).intValue());
        return  res;
    }


    /**
     * 计算任务超期
     */
    @Override
    public void calculateTaskOverdue() {
          projectListNodeMapper.calculateTaskOverdue();
    }

    /**
     * 计算项目超时
     */
    @Override
    public void calculateProjectOverdue() {
        //先初始化超期时间为0
        projectListNodeMapper.initProjectOverdue();
        //再计算超期的工单
        List<JSONObject> list = projectListNodeMapper.queryOverDueProjectList();
        if(!CollectionUtils.isEmpty(list)){
            for (JSONObject jsonObject : list) {
                projectListNodeMapper.calculateProjectOverdue(jsonObject);
            }
        }



    }

    @Override
    public AjaxResult totalProjectForUser(Integer userFlag) {
        JSONObject param = new JSONObject();
        if(userFlag != 0){
            LoginUser loginUser = SecurityUtils.getLoginUser();
            param.put("userId",loginUser.getUserId());
        }

        JSONObject res = projectListNodeMapper.totalProjectForUser(param);
        return AjaxResult.success(res);
    }


    /**
     * 查询未开始BUGLIST的项目列表
     * @param projectList
     * @return
     */
    @Override
    public List<ProjectListVO> queryProjectListNoBug(ProjectList projectList) {
        return   projectListMapper.queryProjectListNoBug(projectList);

    }

    /**
     * 查询是否是第一任务
     * @param projectListNodeMemberId
     * @return
     */
    @Override
    public AjaxResult queryTaskIndex(Long projectListNodeMemberId) {
        List<JSONObject> list = projectListMapper.queryTaskIndex(projectListNodeMemberId);
        return AjaxResult.success(list);
    }

    @Override
    @Transactional
    public AjaxResult modifyProject(ProjectModifyRecord projectModifyRecord) throws Exception {

        if("10".equals(projectModifyRecord.getType())){
            if(CollectionUtils.isEmpty(projectModifyRecord.getProjectModifyRecordDetailList())){
                return AjaxResult.error("明细不能为空");
            }

            int num = 0 ;
            for (ProjectModifyRecordDetail projectModifyRecordDetail : projectModifyRecord.getProjectModifyRecordDetailList()) {
                if(StringUtils.isBlank(projectModifyRecordDetail.getNewEndTime())){
                    num++;
                }
            }

            if(num == projectModifyRecord.getProjectModifyRecordDetailList().size()){
                return AjaxResult.error("明细表不能所有列结束变更时间为空");
            }
        }else{

            ProjectList projectList = projectListMapper.selectById(projectModifyRecord.getProjectListId());
            projectModifyRecord.setOldProjectManager(projectList.getProjectManager());
        }

        LoginUser loginUser = SecurityUtils.getLoginUser();

        projectModifyRecord.setCreateBy(loginUser.getUserId());
        projectModifyRecord.setCreateTime(new Date());
        projectModifyRecord.setStatus(5);
        projectModifyRecordMapper.insert(projectModifyRecord);


        if("10".equals(projectModifyRecord.getType())){//变更时间
            for (ProjectModifyRecordDetail projectModifyRecordDetail : projectModifyRecord.getProjectModifyRecordDetailList()) {
                if(StringUtils.isNotBlank(projectModifyRecordDetail.getNewEndTime())){
                    if(StringUtils.isBlank(projectModifyRecordDetail.getNewStartTime())){
                        projectModifyRecordDetail.setNewStartTime(projectModifyRecordDetail.getStartTime());
                    }
                    projectModifyRecordDetail.setProjectModifyRecordId(projectModifyRecord.getId());
                    projectModifyRecordDetailMapper.insert(projectModifyRecordDetail);
                }
            }
        }


        //启动OA流程
        JSONObject res = startOAProcess(projectModifyRecord,loginUser,false);
        if(!res.getBoolean("success")){
            throw new Exception("推送OA异常!"+res.getString("errorInfo"));
        }

        ProjectModifyRecord update = new ProjectModifyRecord();
        update.setOaId(res.getString("data"));
        update.setId(projectModifyRecord.getId());
        projectModifyRecordMapper.updateById(update);

        addProjectOperLog(projectModifyRecord.getProjectListId(),ProjectListStatusEnum.WAY.getStatus(),"变更项目!");

        return AjaxResult.success("操作成功!");
    }


    @DataSource(DataSourceType.OA)
    public List<JSONObject> queryDiscardProcess(List<ProjectModifyRecord> list) {

        return  oaMapper.queryDiscardProcess(list);

    }

    @Override
    public List<JSONObject> listLog(Long projectListId) {
        return  projectListMapper.listLog(projectListId);
    }


    /**
     * 任务超期或者即将通知的消息通知
     */
    @Override
    public void notice() {

        List<JSONObject> overList = projectListMapper.queryOverdueTask();
        if(!CollectionUtils.isEmpty(overList)){
            for (JSONObject jsonObject : overList) {
                String subject = "你有"+jsonObject.getIntValue("wcq")+" 个任务即将超期；"+jsonObject.getIntValue("cq")+" 个任务已超期，请及时处理；";
                List<String> noticUsers = new ArrayList<>();
                noticUsers.add(jsonObject.getString("companyWechatId"));

                //oaService.createWaitTaskNotice("/project/TaskList",toUsers,ProjectConstants.OA_TODO_SUBJECT+": "+message);

                String token = weChatUtils.getAccessToken();
                AjaxResult res = weChatUtils.sendTextMessage(token,subject,noticUsers);
                if(res.isError()){
                    logger.error("任务超期或者即将通知的消息通知错误:"+res.get(AjaxResult.MSG_TAG));
                }
            }
        }




    }

    /**
     * 邮件通知管理员和项目经理超期的任务
     */
    @Override
    public void emailNotice() {
        List<OverdueTaskListVO> overList = projectListMapper.queryOverdueList();
        if(!CollectionUtils.isEmpty(overList)){
            //设置收件人
            Set<String> emails = new HashSet<>();
            for (OverdueTaskListVO overdueTaskListVO : overList) {
                emails.add(overdueTaskListVO.getEmail());
            }

            //生成excel
            ExcelUtil<OverdueTaskListVO> util = new ExcelUtil<>(OverdueTaskListVO.class);
            AjaxResult result = util.exportExcel(overList, "超期任务数据");
            if(result.isSuccess()){
                //收件人增加相关配置人员
                SysConfig sysConfig = new SysConfig();
                sysConfig.setConfigKey("TASK_OVER_NOTICE_USERS");
                SysConfig emailsConfig = sysConfigMapper.selectConfig(sysConfig);

                //系统重命名后的文件名
                String fileName = result.get("msg").toString();
                String path = PMConfig.getDownloadPath()+ fileName;
                MailRequest mailRequest = new MailRequest();
                mailRequest.setSubject("PM系统任务超期明细");
                mailRequest.setText("PM系统任务超期明细请查看附件");
                mailRequest.setFileName("超期任务列表.xlsx");
                String mt = emails.toString().replaceAll("\\[","").replaceAll("]","");
                mailRequest.setSendTo(emailsConfig.getConfigValue()+","+mt);
//                mailRequest.setSendTo(emailsConfig.getConfigValue());
                mailRequest.setFilePath(path);
                emailUtils.sendHtmlMail(mailRequest);
            }
        }

    }


    @Override
    public AjaxResult modifyTaskUser(ProjectListNodeMember projectListNodeMember) {
        projectListMemberMapper.modifyTaskUser(projectListNodeMember);
        SysUser sysUser = sysUserMapper.selectUserById(projectListNodeMember.getUserId());
        List<String> noticUsers = new ArrayList<>();
        noticUsers.add(sysUser.getCompanyWechatId());
        String subject = ProjectConstants.OA_TODO_SUBJECT+": "+"你有新的代办任务请及时处理;";
        String token = weChatUtils.getAccessToken();
        AjaxResult res = weChatUtils.sendTextMessage(token,subject,noticUsers);
        if(res.isError()){
            logger.error("PM修改责任人发送企业微信消息给处理人错误:"+res.get(AjaxResult.MSG_TAG));
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 项目设置成员保存草稿
     * @param param
     * @return
     */
    @Override
    @Transactional
    public AjaxResult saveSettimeMemberDraft(JSONObject param) {

        JSONArray nodes = param.getJSONArray("nodes");

        JSONObject iobj = new JSONObject();
        iobj.put("index",1);


        //先删除草稿
        projectListNodeMapper.deleteDraft(param.getLong("id"));

        if(!CollectionUtils.isEmpty(nodes)){
            for(int i=0;i< nodes.size();i++){
                JSONObject item = nodes.getJSONObject(i);

                 //草稿保存时间
                if(!CollectionUtils.isEmpty(item.getJSONArray("roundDate"))){
                    ProjectListNode projectListNode = new ProjectListNode();
                    projectListNode.setId(item.getLong("pnId"));
                    JSONArray times = item.getJSONArray("roundDate");
                    projectListNode.setStartTime(times.getString(0));
                    projectListNode.setEndTime(times.getString(1));
                    projectListNodeMapper.addProjectNodeMembersTimeDraft(projectListNode);
                }


                if(!CollectionUtils.isEmpty(item.getJSONArray("children"))){
                    //获取节点责任人
                    setTimeForNodeDraft(item,iobj);
                }
            }
        }


        return AjaxResult.success("操作成功!");
    }

    @Override
    public AjaxResult getSetupDetailDraft(Long projectListId) {

        JSONObject res = new JSONObject();
        //查询节点信息
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();


        List<ProjectTempleteDefine> nodes = projectListNodeMapper.getProjectNodesDraft(projectListId,sysUser.getUserId());
        if(!CollectionUtils.isEmpty(nodes)){

            List<ProjectTempleteDefine>  treeList = ProjectUtils.buildProjectTempleteDefineTree(nodes);
            List<TreeSelect> ts = treeList.stream().map(TreeSelect::new).collect(Collectors.toList());
            //版本号
            res.put("versionNo",nodes.get(0).getVersionNo());
            //树状接口任务列表
            res.put("trees",ts);

            res.put("treeList",treeList);

            //计算里程碑完成率
            if(!CollectionUtils.isEmpty(treeList)){
                for (ProjectTempleteDefine projectTempleteDefine : treeList) {
                    List<String> roundDate = new ArrayList<>();
                    if(StringUtils.isNotBlank(projectTempleteDefine.getStartTime())){
                        roundDate.add(projectTempleteDefine.getStartTime());
                    }

                    if(StringUtils.isNotBlank(projectTempleteDefine.getEndTime())){
                        roundDate.add(projectTempleteDefine.getEndTime());
                    }


                    projectTempleteDefine.setRoundDate(roundDate);
                }
            }



        }
        return AjaxResult.success(res);

    }


    /**
     * 驳回项目
     * @param param
     * @return
     */
    @Override
    public AjaxResult rejectSetUp(JSONObject param) {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        ProjectList projectList = new ProjectList();
        projectList.setId(param.getLong("id"));
        projectList.setUpdateTime(new Date());
        projectList.setUpdateBy(loginUser.getUserId());
        projectList.setStatus(ProjectListStatusEnum.REJECT.getStatus());
        projectListMapper.updateById(projectList);

        addProjectOperLog(projectList.getId(),ProjectListStatusEnum.CREATE.getStatus(),"驳回项目:"+param.getString("remark"));

        //企业微信通知
        MPJLambdaWrapper<ProjectList> query = JoinWrappers.lambda(ProjectList.class);
        query.innerJoin(SysUser.class,"s",SysUser::getUserId,ProjectList::getCreateBy)
                .selectAs("s",SysUser::getCompanyWechatId, ProjectListVO::getCreateCompanyWechatId)
                .selectAll(ProjectList.class);
        query.eq(ProjectList::getId,projectList.getId());
        ProjectListVO vo = projectListMapper.selectJoinOne(ProjectListVO.class,query);
        List<String> noticUsers = new ArrayList<>();
        noticUsers.add(vo.getCreateCompanyWechatId());

        String subject = ProjectConstants.OA_TODO_SUBJECT+": "+vo.getProductName()+" 被驳回，驳回原因: "+param.getString("remark")+"请登陆系统查看!";
        String token = weChatUtils.getAccessToken();
        AjaxResult res = weChatUtils.sendTextMessage(token,subject,noticUsers);
        if(res.isError()){
            logger.error("PM 驳回项目发送企业微信消息给项目经理错误:"+res.get(AjaxResult.MSG_TAG));
        }
//        oaService.createWaitTaskNotice("/project/ProjectList",toUsers,ProjectConstants.OA_TODO_SUBJECT+": "+vo.getProductName()+" 被驳回，请登陆系统查看!");
        return AjaxResult.success("操作成功！");
    }


    /**
     * 项目经理驳回项目到项目设置环节
     * @param param
     * @return
     */
    @Override
    public AjaxResult rejectProject(JSONObject param) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        ProjectList projectList = new ProjectList();
        projectList.setId(param.getLong("id"));
        projectList.setUpdateTime(new Date());
        projectList.setUpdateBy(loginUser.getUserId());
        projectList.setStatus(ProjectListStatusEnum.CREATE.getStatus());
        projectListMapper.updateById(projectList);

        addProjectOperLog(projectList.getId(),ProjectListStatusEnum.DEFINE.getStatus(),"驳回项目:"+param.getString("remark"));

        SysConfig sysConfig = new SysConfig();
        sysConfig.setConfigKey(ProjectConstants.PROJECT_LIST_SET_NOTICE);
        SysConfig jobNumbers = sysConfigMapper.selectConfig(sysConfig);
        if(jobNumbers != null && StringUtils.isNotBlank(jobNumbers.getConfigValue())){
            ProjectList vo = projectListMapper.selectById(param.getLong("id"));
            String[] jobs = jobNumbers.getConfigValue().split(";");
            List<String> noticUsers =  Arrays.stream(jobs).collect(Collectors.toList());
            String subject = ProjectConstants.OA_TODO_SUBJECT+": "+vo.getProductName()+"被驳回，驳回原因:"+param.getString("remark")+"，请登陆系统查看!";
            String token = weChatUtils.getAccessToken();
            AjaxResult res = weChatUtils.sendTextMessage(token,subject,noticUsers);
            if(res.isError()){
                logger.error("项目经理驳回项目到项目设置环节发送企业微信消息给处理人错误:"+res.get(AjaxResult.MSG_TAG));
            }
//        oaService.createWaitTaskNotice("/project/setup",toUsers,ProjectConstants.OA_TODO_SUBJECT+": "+vo.getProductName()+"被驳回，请登陆系统查看!");

        }
        return AjaxResult.success("操作成功！");
    }

    @Override
    public AjaxResult getSetup(Long projectListId) {
        List<Integer> pnids = projectListNodeMapper.getSetup(projectListId);
        return AjaxResult.success(pnids);
    }

    @Override
    public AjaxResult restart(ProjectList projectList) {

        //查询中止前的状态
        QueryWrapper<ProjectListStop> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_list_id",projectList.getId());
        queryWrapper.eq("status",1);
        ProjectListStop projectListStop = projectListStopMapper.selectOne(queryWrapper);

        //更新状态
        projectList.setStatus(projectListStop.getProjectListStatus());
        projectListMapper.updateById(projectList);

        projectListStop.setStatus(0);
        projectListStopMapper.updateById(projectListStop);
        addProjectOperLog(projectList.getId(),ProjectListStatusEnum.STOP.getStatus(),"重启项目");
        return AjaxResult.success("重启成功!");
    }

    /**
     * 删除项目节点
     * @param projectListNode
     * @return
     */
    @Override
    @Transactional
    public AjaxResult deleteNode(ProjectListNode projectListNode) {

        ProjectListNode projectListNodeRes = projectListNodeMapper.selectById(projectListNode.getId());
        //删除节点
        projectListNodeMapper.deleteById(projectListNode.getId());
        //删除任务
        QueryWrapper<ProjectListNodeMember> mpjLambdaWrapper = new QueryWrapper<>();
        mpjLambdaWrapper.eq("project_list_node_id",projectListNode.getId());
        projectListNodeMemberMapper.delete(mpjLambdaWrapper);

        //判断父节点是否还有子节点
        projectListNodeRes.setParentId(projectListNode.getParentId());
        List<JSONObject> childrens = projectListNodeMapper.hasChildrenNode(projectListNodeRes);
        if(CollectionUtils.isEmpty(childrens)){//已无子节点

            //删除父节点
            projectListNodeMapper.delParentNode(projectListNodeRes);
        }

        ProjectListVO projectListVO = new ProjectListVO();
        projectListVO.setId(projectListNodeRes.getProjectListId());
        oaService.checkProjectDone(projectListVO);

        addProjectOperLog(projectListNodeRes.getProjectListId(),ProjectListStatusEnum.WAY.getStatus(),String.format("删除 [%s] 节点",projectListNode.getNodeName()));
        return AjaxResult.success("操作成功!");
    }

    /**
     * 添加项目成员
     * @param projectListMemberVO
     * @return
     */
    @Override
    public AjaxResult addProjectMember(ProjectListMemberVO projectListMemberVO) {
        //先查询此项目成员和类型是否重复
        MPJLambdaWrapper<ProjectListMember> mpjLambdaWrapper = new MPJLambdaWrapper<>();
        mpjLambdaWrapper.eq(ProjectListMember::getProjectListId,projectListMemberVO.getProjectListId())
                .eq(ProjectListMember::getUserId,projectListMemberVO.getUserId())
                .eq(ProjectListMember::getType,projectListMemberVO.getType());
        List<ProjectListMember> users = projectListMemberMapper.selectList(mpjLambdaWrapper);
        if(!CollectionUtils.isEmpty(users)){
            return AjaxResult.error("此用户此岗位在项目成员中已存在!");
        }

        ProjectListMember projectListMember = new ProjectListMember();
        BeanUtils.copyProperties(projectListMemberVO,projectListMember);
        projectListMemberMapper.insert(projectListMember);
        return AjaxResult.success("操作成功!");
    }

    /**
     * 替换项目成员
     * @param projectListMemberVO
     * @return
     */
    @Override
    public AjaxResult replaceProjectMember(ProjectListMemberVO projectListMemberVO) {
        //先判断项目成员表是否存在 已存在则不再修改 直接删除
        MPJLambdaWrapper<ProjectListMember> mpjLambdaWrapper = new MPJLambdaWrapper<>();
        mpjLambdaWrapper.eq(ProjectListMember::getProjectListId,projectListMemberVO.getProjectListId())
                .eq(ProjectListMember::getType,projectListMemberVO.getType())
                .eq(ProjectListMember::getUserId,projectListMemberVO.getNewUserId());
        List<ProjectListMember> list = projectListMemberMapper.selectList(mpjLambdaWrapper);
        if(!CollectionUtils.isEmpty(list)){
            projectListMemberMapper.deleteById(projectListMemberVO.getId());
        }else{
            ProjectListMember update = new ProjectListMember();
            update.setId(projectListMemberVO.getId());
            update.setUserId(projectListMemberVO.getNewUserId());
            projectListMemberMapper.updateById(update);
        }

        //修改任务的责任人
        projectListNodeMemberMapper.modifyTaskUser(projectListMemberVO);

        return AjaxResult.success("操作成功!");
    }

    /**
     * 同步项目进度
     */
    @Override
    public void sysProcess() {
        List<ProjectList> list = projectListMapper.selectList(null);
        for (ProjectList projectList : list) {
          JSONObject res= queryProgress(projectList);
          ProjectList  update = new ProjectList();
            update.setId(projectList.getId());
            update.setProgress(res.getBigDecimal("progress"));
            projectListMapper.updateById(update);
        }

    }

    /**
     * 启动OA流程
     * @param projectModifyRecord
     * @return
     */
    private JSONObject startOAProcess(ProjectModifyRecord projectModifyRecord,LoginUser loginUser,boolean isUpdate) {
        Review review = new Review();

        SysConfig sysConfig = new SysConfig();
        sysConfig.setConfigKey(ProjectConstants.PROJECT_MODIFY_OA_ID);
        SysConfig config = sysConfigMapper.selectConfig(sysConfig);
        review.setFdTemplateId(config.getConfigValue());

        review.setDocStatus(ProjectConstants.OA_STATUS_WAIT_APPROVE);
        //提交人工号
        JSONObject creator = new JSONObject();
        creator.put("LoginName",loginUser.getUser().getJobNumber());
        review.setDocCreator(creator.toJSONString());
        review.setFdNumber(UUID.randomUUID().toString());

        AjaxResult result = detail(String.valueOf(projectModifyRecord.getProjectListId()));
        ProjectListVO projectListVO =(ProjectListVO) result.get("data");

        JSONObject formValues = new JSONObject();
        formValues.put("fd_3df0cfc71ab766",projectListVO.getProjectNo());
        formValues.put("fd_3df0cfcc490f5c",projectListVO.getProjectName());
        formValues.put("fd_3df0cfccb74620",projectListVO.getProjectManagerName());
        formValues.put("fd_3df0d001675282",projectModifyRecord.getRemark());
        formValues.put("fd_3e9aa8ade47794",projectModifyRecord.getType());
        review.setDocSubject(projectListVO.getProjectNo()+"项目变更申请");

        if("10".equals(projectModifyRecord.getType())){//变更时间
            //明细
            List<ProjectModifyRecordDetail> details =  projectModifyRecordMapper.queryProjectModifyRecordDetail(projectModifyRecord);

            List<JSONObject> mxList = new ArrayList<>();
            for (ProjectModifyRecordDetail detail : details) {
                JSONObject item = new JSONObject();
                item.put("fd_3df0d014d3aa8c.fd_3df0d03fb607bc",detail.getNodeName());
                item.put("fd_3df0d014d3aa8c.fd_3df0d0403caa18",detail.getStartTime());
                item.put("fd_3df0d014d3aa8c.fd_3df0d040b19ca2",detail.getEndTime());
                item.put("fd_3df0d014d3aa8c.fd_3df0d041205dde",detail.getNewStartTime());
                item.put("fd_3df0d014d3aa8c.fd_3df0d0418bbfa2",detail.getNewEndTime());
                item.put("fd_3df0d014d3aa8c.fd_3df0d058212a62",detail.getRemark());
                mxList.add(item);
            }
            //明细表
            formValues.put("fd_3df0d014d3aa8c",mxList);
        }else{//变更项目经理
            formValues.put("fd_3e9aa8d15e927a",projectModifyRecord.getModifyProjectManagerName());//变更后的项目经理名称
            formValues.put("fd_3e9aa8e4497e2a",projectModifyRecord.getModifyProjectManagerId());//变更后的项目经理ID
        }

        review.setFormValues(formValues);
        review.setFdSource(ProjectConstants.SYSTEM_NAME);
        JSONObject res = new JSONObject();
        if(isUpdate){
            review.setFdId(projectModifyRecord.getOaId());
            res =  oaUtils.updateReview(review);
        }else{
            res =  oaUtils.addReview3(review);
        }

        logger.info("启动OA项目文件审批流程返回参数:"+res);
        return res;
    }

    @Override
    public List<ProjectModifyRecord> queryProjectModifyRecord(ProjectList projectList) {
        MPJLambdaWrapper<ProjectModifyRecord> queryWrapper = JoinWrappers.lambda();
        queryWrapper.leftJoin(SysUser.class,"p",SysUser::getUserId,ProjectModifyRecord::getModifyProjectManagerId)
                .leftJoin(SysUser.class,"s",SysUser::getUserId,ProjectModifyRecord::getOldProjectManager)
                .selectAs("p",SysUser::getNickName,ProjectModifyRecord::getModifyProjectManagerName)
                .selectAs("s",SysUser::getNickName,ProjectModifyRecord::getOldProjectManagerName)
                .selectAll(ProjectModifyRecord.class);
        queryWrapper.eq("project_list_id",projectList.getId());
        return projectModifyRecordMapper.selectJoinList(ProjectModifyRecord.class,queryWrapper);
    }

    @Override
    public List<ProjectModifyRecordDetail> queryProjectModifyRecordDetail(ProjectModifyRecord projectModifyRecord) {
        return projectModifyRecordMapper.queryProjectModifyRecordDetail(projectModifyRecord);
    }

    @Override
    @Transactional
    public AjaxResult updateModifyProject(ProjectModifyRecord projectModifyRecord) throws Exception {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        ProjectModifyRecord update = new ProjectModifyRecord();
        update.setId(projectModifyRecord.getId());
        update.setStatus(5);
        update.setRemark(projectModifyRecord.getRemark());
        update.setUpdateBy(loginUser.getUserId());
        projectModifyRecordMapper.updateById(update);

        //先删除
        QueryWrapper<ProjectModifyRecordDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_modify_record_id",projectModifyRecord.getId());
        projectModifyRecordDetailMapper.delete(queryWrapper);

        for (ProjectModifyRecordDetail projectModifyRecordDetail : projectModifyRecord.getProjectModifyRecordDetailList()) {
            if(StringUtils.isNotBlank(projectModifyRecordDetail.getNewEndTime())){
                if(StringUtils.isBlank(projectModifyRecordDetail.getNewStartTime())){
                    projectModifyRecordDetail.setNewStartTime(projectModifyRecordDetail.getStartTime());
                }
                projectModifyRecordDetail.setProjectModifyRecordId(projectModifyRecord.getId());
                projectModifyRecordDetailMapper.insert(projectModifyRecordDetail);
            }
        }

        //启动OA流程
        JSONObject res = startOAProcess(projectModifyRecord,loginUser,true);
        if(!res.getBoolean("success")){
            throw new Exception("推送OA异常!"+res.getString("errorInfo"));
        }
        return AjaxResult.success("操作成功!");
    }

    /**
     * 查询变更详情
     * @param projectModifyRecord
     * @return
     */
    @Override
    public List<ProjectModifyRecordDetail> queryProjectModifyRecordForDetail(ProjectModifyRecord projectModifyRecord) {

        return projectListNodeMapper.queryProjectModifyRecordForDetail(projectModifyRecord);

    }

    /**
     * 根节点时间
     * @param nodes
     */
    private void rootNodesTimes(JSONArray nodes,String projectNo) {

            JSONObject iobj = new JSONObject();
            iobj.put("index",1);

            for(int i=0;i< nodes.size();i++){
                JSONObject item = nodes.getJSONObject(i);

                //更新时间
                ProjectListNode projectListNode = new ProjectListNode();
                projectListNode.setId(item.getLong("pnId"));
                JSONArray times = item.getJSONArray("roundDate");
                projectListNode.setStartTime(times.getString(0));
                projectListNode.setEndTime(times.getString(1));
                projectListNodeMapper.updateById(projectListNode);


                if(!CollectionUtils.isEmpty(item.getJSONArray("children"))){
                    //获取节点时间
                    setTimeForNode(item,iobj,projectNo);
                }
            }

    }




    /**
     * 设置节点时间保存草稿
     * @param
     *
     */
    private void setTimeForNodeDraft(JSONObject node,JSONObject iobj ) {
        JSONArray array =  node.getJSONArray("children");
        for(int i=0;i<array.size();i++){
            JSONObject item = array.getJSONObject(i);
            if(!CollectionUtils.isEmpty(item.getJSONArray("children"))){
                setTimeForNodeDraft(item,iobj);
            }else{
                JSONArray projectListNodeMemberList = item.getJSONArray("projectListNodeMemberList");
                if(!CollectionUtils.isEmpty(projectListNodeMemberList)){
                    for(int j=0;j<projectListNodeMemberList.size();j++){
                        JSONObject obj = projectListNodeMemberList.getJSONObject(j);
                        JSONArray  roundDate = node.getJSONArray("roundDate");
                        if(!CollectionUtils.isEmpty(roundDate) && roundDate.size() > 1){
                            String startTime = roundDate.getString(0);
                            obj.put("startTime",startTime);
                            String endTime = roundDate.getString(1);
                            obj.put("endTime",endTime);
                        }

                    }
                    JSONArray projectListNodeMembers = item.getJSONArray("projectListNodeMemberList");
                    for(int j=0;j<projectListNodeMembers.size();j++){

                        JSONObject obj = projectListNodeMembers.getJSONObject(j);
                        if(!ObjectUtils.isEmpty(obj) && obj.getLong("userId") != null){
                            obj.put("pnId",item.getString("pnId"));
                            projectListNodeMapper.addProjectNodeMembersDraft(obj);
                        }


                    }
                }
            }
        }


    }




    /**
     * 设置节点时间
     * @param
     *
     */
    private void setTimeForNode(JSONObject node,JSONObject iobj,String projectNo) {
        JSONArray array =  node.getJSONArray("children");
        for(int i=0;i<array.size();i++){
            JSONObject item = array.getJSONObject(i);
            if(!CollectionUtils.isEmpty(item.getJSONArray("children"))){
                setTimeForNode(item,iobj,projectNo);
            }else{
                JSONArray projectListNodeMemberList = item.getJSONArray("projectListNodeMemberList");
                if(!CollectionUtils.isEmpty(projectListNodeMemberList)){
                    for(int j=0;j<projectListNodeMemberList.size();j++){
                        JSONObject obj = projectListNodeMemberList.getJSONObject(j);
                        JSONArray  roundDate = node.getJSONArray("roundDate");
                        if(!CollectionUtils.isEmpty(roundDate) && roundDate.size() > 1){
                            String startTime = roundDate.getString(0);
                            obj.put("startTime",startTime);
                            String endTime = roundDate.getString(1);
                            obj.put("endTime",endTime);
                         }

                    }
                    JSONArray projectListNodeMembers = item.getJSONArray("projectListNodeMemberList");
                    for(int j=0;j<projectListNodeMembers.size();j++){
                        int index = iobj.getIntValue("index");
                        JSONObject obj = projectListNodeMembers.getJSONObject(j);
                        obj.put("pnId",item.getString("pnId"));
                        obj.put("taskNo",projectNo+String.format("%03d", index));
                        projectListNodeMapper.addProjectNodeMembers(obj);
                        index++;
                        iobj.put("index",index);
                    }
                }
            }
        }


    }


}
